package com.sofwin.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sofwin.Constants;
import com.sofwin.dto.NavsDto;
import com.sofwin.dto.TreeNodeDto2;
import com.sofwin.pojo.SUser;
import com.sofwin.service.ResourceService;
import com.sofwin.service.UserService;

@Controller
@RequestMapping("/system")
public class SystemController {
	public  Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private ResourceService resourceService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/resources")
	@ResponseBody
	public List<NavsDto> getResources(HttpSession session){
		SUser user = (SUser)session.getAttribute(Constants.CURRENT_USER);
		return resourceService.listResourcesByRoleId(user.getRoleId());
	}
	@RequestMapping("/resource/data")
	public String toResource(Model model) throws JsonProcessingException {
		List<TreeNodeDto2> data = resourceService.selectResource_();
		ObjectMapper mapper = new ObjectMapper();
		String str = mapper.writeValueAsString(data);
		System.out.println(str);
		model.addAttribute("data", str);
		return "resource";
	}
	
	@RequestMapping("toLogin")

	public String toLogin() {
		logger.debug("******************redirect to login");
		return "redirect:/login.jsp";
	}
	@PostMapping("checkLogin")
	public String checkLogin(SUser user,HttpSession session,String code) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPwd());
		try {
		// 将身份认证交给shiro来做
		subject.login(token);
		subject.hasRole("2");
		}catch(UnknownAccountException ex) {
			// 用户名不存在
			toLogin();
		}catch(IncorrectCredentialsException ex) {
			// 密码错误
			toLogin();
		}
		// 登录成功
		user = userService.selectUserByUserNameAndPwd(user);
		session.setAttribute(Constants.CURRENT_USER, user);
		return "index";
	}
	@RequestMapping("logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return toLogin();
	}

}
